package com.example.controller;

import com.example.bean.Result;
import com.example.bean.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户登录与注册
 */
@Slf4j
@RestController
public class UserController {
    @Autowired
    UserService userService;

    //用户登录
    @PostMapping(value = "/api/userLogin")
    @CrossOrigin       //后端跨域
    public Result login(@RequestParam("uname") String uname, @RequestParam("upassword") String upassword) {
        return userService.login(uname, upassword);
    }

    //用户注册
    @PostMapping(value = "/api/UserRegister")
    @CrossOrigin       //后端跨域
    public Result register(@RequestBody User user) {
        User us = userService.SelectUser(user.getUName());
        if (us != null) {
            //注册失败，用户已经存在，返回注册页面
            return new Result(401, "注册失败，用户已经存在", "");
        }
        //查找用户uid的最大值
        int maxuId = userService.SelectMaxuId();
        //将uid的最大值+1，作为刚刚注册的用户的uid
        int result = userService.registerUser(maxuId + 1, user.getUName(), user.getUSex(), user.getUPhone(), user.getUPassword(), user.getUEmail());
        if (result == 0) {
            //注册失败，跳转注册页面
            return new Result(400, "注册失败", "");
        }
        System.out.println(1111);
        //注册成功，跳转登录页面
        return new Result(200, "注册成功", "");
    }
}
